package com.limmg.code_generate.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.File;
import java.nio.file.Files;

public class CodeGenerator {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://XXXXXXXXXXX:3306/XXXXXXXXXX";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "ROOT";
    
    // 包名
    private static final String BASE_PACKAGE = "com.limmg.code_generate";
    // 模板路径
    private static final String TEMPLATE_PATH = "src/main/resources/templates";

    // 主方法, 传入表名即可生成对应的代码
    public static void main(String[] args) {
        System.out.println("开始生成代码");
        // 定义要生成的表名列表
        String[] tables = {"employee", "employee_copy1", "employee_copy2"};
        generateBatch(tables);
        System.out.println("生成完成!!!");
    }
    
    /**
     * 批量生成代码
     * @param tables 表名数组
     */
    public static void generateBatch(String[] tables) {
        if (tables == null || tables.length == 0) {
            System.out.println("没有需要生成的表!");
            return;
        }
        
        for (String tableName : tables) {
            try {
                System.out.println("开始生成表: " + tableName);
                generate(tableName);
                System.out.println("表: " + tableName + " 生成完成");
            } catch (Exception e) {
                System.err.println("生成表: " + tableName + " 失败");
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 生成指定数据库中的所有表
     */
    public static void generateAll() {
        String[] tables = getAllTables();
        generateBatch(tables);
    }

    /**
     * 从数据库中获取所有表名
     * @return 表名数组
     */
    public static String[] getAllTables() {
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
            
            List<String> tableList = new ArrayList<>();
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                tableList.add(tableName);
            }
            
            return tableList.toArray(new String[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return new String[0];
        }
    }
    
    private static String capitalizeFirstLetter(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    
    /**
     * 将表名转换为类名（驼峰命名）
     * 例如：user_info -> UserInfo, t_user_info -> UserInfo
     */
    private static String tableNameToClassName(String tableName) {
        // 如果表名以't_'或'tbl_'开头，去掉这个前缀
        if (tableName.startsWith("t_") || tableName.startsWith("tbl_")) {
            tableName = tableName.substring(tableName.indexOf('_') + 1);
        }
        
        StringBuilder result = new StringBuilder();
        // 标记是否是新单词的开始
        boolean nextUpperCase = true;
        
        for (int i = 0; i < tableName.length(); i++) {
            char c = tableName.charAt(i);
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    result.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        
        return result.toString();
    }

    public static void generate(String tableName) {
        try {
            // 使用新的方法生成类名
            String className = tableNameToClassName(tableName);
            
            // 创建数据库连接
            Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
            try {
                DatabaseMetaData metaData = conn.getMetaData();
                ResultSet columns = metaData.getColumns(null, null, tableName, null);
                
                // 2. 生成实体类
                generatePo(className, tableName, columns);
                columns.beforeFirst(); // 重置ResultSet
                // 3. 生成DTO
                generateDto(className, tableName, columns);
                columns.beforeFirst();
                // 4. 生成VO
                generateVo(className, tableName, columns);
                columns.beforeFirst();
                // 5. 生成Param
                generateParam(className, tableName, columns);
                columns.beforeFirst();
                // 6. 生成Mapper
                generateMapper(className);
                // 7. 生成XML
                generateXml(className, tableName, columns, conn);
                // 8. 生成Service
                generateService(className);
                // 9. 生成Controller
                generateController(className);
                
                // 生成Converter
                generateConverter(className);
                
            } finally {
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static String toCamelCase(String columnName) {
        StringBuilder result = new StringBuilder();
        boolean nextUpper = false;
        
        for (int i = 0; i < columnName.length(); i++) {
            char currentChar = columnName.charAt(i);
            if (currentChar == '_') {
                nextUpper = true;
            } else {
                if (nextUpper) {
                    result.append(Character.toUpperCase(currentChar));
                    nextUpper = false;
                } else {
                    result.append(currentChar);
                }
            }
        }
        return result.toString();
    }
    
    private static void generatePo(String className, String tableName, ResultSet columns) throws Exception {
        String poClassName = generatePoClassName(tableName);
        StringBuilder fields = new StringBuilder();
        StringBuilder imports = new StringBuilder();
        
        // 只添加可能需要的特殊导包
        boolean needDateImport = false;
        boolean needBigDecimalImport = false;
        
        // 重置ResultSet
        columns.beforeFirst();
        
        // 使用统一的generateFields方法生成字段
        generateFields(columns, fields);
        
        // 检查是否需要特殊导包
        if (fields.toString().contains("Date")) {
            imports.append("import java.util.Date;\n");
        }
        if (fields.toString().contains("BigDecimal")) {
            imports.append("import java.math.BigDecimal;\n");
        }
        
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/entity.template");
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("poClassName", poClassName);
        params.put("tableName", tableName);
        params.put("fields", fields.toString());
        params.put("imports", imports.toString());
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/model/po/" + poClassName + ".java", content);
    }

    private static void generateDto(String className, String tableName, ResultSet columns) throws Exception {
        String dtoClassName = generateDtoClassName(tableName);
        StringBuilder fields = new StringBuilder();
        StringBuilder imports = new StringBuilder();
        
        // 只添加可能需要的特殊导包
        boolean needDateImport = false;
        boolean needBigDecimalImport = false;
        
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String camelCaseColumnName = toCamelCase(columnName);
            String columnType = columns.getString("TYPE_NAME");
            String remarks = columns.getString("REMARKS");
            String javaType = mapColumnType(columnType);
            
            if (javaType.equals("Date") && !needDateImport) {
                needDateImport = true;
                imports.append("import java.util.Date;\n");
            }
            
            if (javaType.equals("BigDecimal") && !needBigDecimalImport) {
                needBigDecimalImport = true;
                imports.append("import java.math.BigDecimal;\n");
            }
            
            fields.append("    /**\n")
                  .append("     * ").append(remarks).append("\n")
                  .append("     */\n")
                  .append("    @ApiModelProperty(\"").append(remarks).append("\")\n")
                  .append("    private ").append(javaType)
                  .append(" ").append(camelCaseColumnName).append(";\n\n");
        }
        
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/dto.template");
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("dtoClassName", dtoClassName);
        params.put("fields", fields.toString());
        params.put("imports", imports.toString());
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/model/dto/" + dtoClassName + ".java", content);
    }

    private static void generateVo(String className, String tableName, ResultSet columns) throws Exception {
        String voClassName = generateVoClassName(tableName);
        StringBuilder fields = new StringBuilder();
        StringBuilder imports = new StringBuilder();
        boolean needDateImport = false;
        boolean needBigDecimalImport = false;
        
        // 定义BaseVO中已有的字段集合
        Set<String> baseVoFields = new HashSet<>();
        baseVoFields.add("id");
        baseVoFields.add("createTime");
        baseVoFields.add("updateTime");
        baseVoFields.add("createBy");
        baseVoFields.add("updateBy");
        
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String camelCaseColumnName = toCamelCase(columnName);
            String columnType = columns.getString("TYPE_NAME");
            String remarks = columns.getString("REMARKS");
            String javaType = mapColumnType(columnType);
            
            // 跳过BaseVO中已有的字段
            if (baseVoFields.contains(camelCaseColumnName)) {
                continue;
            }
            
            if (javaType.equals("Date") && !needDateImport) {
                needDateImport = true;
                imports.append("import java.util.Date;\n");
            }
            
            if (javaType.equals("BigDecimal") && !needBigDecimalImport) {
                needBigDecimalImport = true;
                imports.append("import java.math.BigDecimal;\n");
            }
            
            fields.append("    /**\n")
                  .append("     * ").append(remarks).append("\n")
                  .append("     */\n")
                  .append("    @ApiModelProperty(\"").append(remarks).append("\")\n")
                  .append("    private ").append(javaType)
                  .append(" ").append(camelCaseColumnName).append(";\n\n");
        }
        
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/vo.template");
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("voClassName", voClassName);
        params.put("fields", fields.toString());
        params.put("imports", imports.toString());
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/model/vo/" + voClassName + ".java", content);
    }

    private static void generateParam(String className, String tableName, ResultSet columns) throws Exception {
        StringBuilder fields = new StringBuilder();
        StringBuilder imports = new StringBuilder();
        boolean needDateImport = false;
        boolean needBigDecimalImport = false;
        
        // 定义BaseParam中已有的字段集合
        Set<String> baseParamFields = new HashSet<>();
        baseParamFields.add("id");  // BaseParam中已有的字段
        
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String camelCaseColumnName = toCamelCase(columnName);
            String columnType = columns.getString("TYPE_NAME");
            String remarks = columns.getString("REMARKS");
            String javaType = mapColumnType(columnType);
            
            // 跳过BaseParam中已有的字段
            if (baseParamFields.contains(camelCaseColumnName)) {
                continue;
            }
            
            if (javaType.equals("Date") && !needDateImport) {
                needDateImport = true;
                imports.append("import java.util.Date;\n");
            }
            
            if (javaType.equals("BigDecimal") && !needBigDecimalImport) {
                needBigDecimalImport = true;
                imports.append("import java.math.BigDecimal;\n");
            }
            
            fields.append("    /**\n")
                  .append("     * ").append(remarks).append("\n")
                  .append("     */\n")
                  .append("    @ApiModelProperty(\"").append(remarks).append("\")\n")
                  .append("    private ").append(javaType)
                  .append(" ").append(camelCaseColumnName).append(";\n\n");
        }
        
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/param.template");
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("fields", fields.toString());
        params.put("imports", imports.toString());
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/model/param/" + className + "Param.java", content);
    }

    private static void generateMapper(String className) throws Exception {
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/mapper.template");
        Map<String, Object> params = Map.of("package", BASE_PACKAGE, "className", className);
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/mapper/" + className + "Mapper.java", content);
    }

    private static void generateXml(String className, String tableName, ResultSet columns, Connection conn) throws Exception {
        // 构建resultMap
        StringBuilder resultMap = new StringBuilder();
        // 构所有字段列表
        StringBuilder fields = new StringBuilder();
        // 构建插入字段
        StringBuilder insertFields = new StringBuilder();
        // 构建插入值
        StringBuilder insertValues = new StringBuilder();
        // 构建批量插入值
        StringBuilder batchInsertValues = new StringBuilder();
        // 构建更新字段
        StringBuilder updateFields = new StringBuilder();
        // 构建where条件
        StringBuilder whereConditions = new StringBuilder();
        
        ResultSet primaryKeys = conn.getMetaData().getPrimaryKeys(null, null, tableName);
        String primaryKey = primaryKeys.next() ? primaryKeys.getString("COLUMN_NAME") : "id";
        String primaryKeyCamel = toCamelCase(primaryKey);  // 转换主键为驼峰命名
        
        // 获取列的类型信息
        ResultSet columnTypes = conn.getMetaData().getColumns(null, null, tableName, null);
        String primaryKeyType = "";
        while (columnTypes.next()) {
            if (columnTypes.getString("COLUMN_NAME").equals(primaryKey)) {
                primaryKeyType = columnTypes.getString("TYPE_NAME");
                break;
            }
        }
        columnTypes.close();
        
        // 添加主键映射
        resultMap.append("        <id column=\"").append(primaryKey)
                .append("\" property=\"").append(primaryKeyCamel)
                .append("\"/>\n");
        
        // 构建带test条件的插入字段
        StringBuilder insertFieldsWithTest = new StringBuilder();
        // 构建带test条件的插入值
        StringBuilder insertValuesWithTest = new StringBuilder();
        // 构建带test条件的批量插入字段
        StringBuilder batchInsertFieldsWithTest = new StringBuilder();
        // 构建带test条件的批量插入值
        StringBuilder batchInsertValuesWithTest = new StringBuilder();
        // 构建带test条件的更新字段
        StringBuilder updateFieldsWithTest = new StringBuilder();
        // 构建带test条件的where条件
        StringBuilder whereConditionsWithTest = new StringBuilder();
        
        // 构建批量插入或更新的字段列表
        StringBuilder batchAddOrUpdateFields = new StringBuilder();
        // 构建批量插入或更新的值列表
        StringBuilder batchAddOrUpdateValues = new StringBuilder();
        // 构建ON DUPLICATE KEY UPDATE的更新列表
        StringBuilder duplicateKeyUpdate = new StringBuilder();
        
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String camelCaseColumnName = toCamelCase(columnName);
            String columnType = columns.getString("TYPE_NAME");
            String jdbcType = getJdbcType(columnType);
            
            // 如果不是主键，添加普通字段映射
            if (!columnName.equals(primaryKey)) {
                resultMap.append("        <result column=\"").append(columnName)
                        .append("\" property=\"").append(camelCaseColumnName)
                        .append("\"/>\n");
            }
            
            // 添加到字段列表
            fields.append(columnName).append(", ");
            
            // 添加到插入字段列表，统一缩进12个空格
            insertFields.append("            ").append(columnName).append(",\n");
            
            // 添加到插入值列表，统一缩进12个空格
            insertValues.append("            #{").append(columnName)
                       .append("},\n");
            
            // 添加到批量插入值列表，统一缩进16个空格
            batchInsertValues.append("                #{item.").append(columnName)
                            .append("},\n");
            
            // 添加到更新字段列表，统一缩进12个空格
            if (!columnName.equals(primaryKey)) {
                updateFields.append("            ").append(columnName).append(" = #{")
                           .append(columnName).append("},\n");
            }
            
            // 添加到where条件，统一缩进12个空格
            whereConditions.append("            AND ").append(columnName).append(" = #{")
                          .append(columnName).append("}\n");
            
            if (!columnName.equals(primaryKey)) {
                // 构建条件判断语句
                String testCondition = camelCaseColumnName + " != null";
                if (isStringType(columnType)) {
                    testCondition += " and " + camelCaseColumnName + " != ''";
                }

                // 插入字段带test条件
                insertFieldsWithTest.append("            <if test=\"")
                                  .append(testCondition)
                                  .append("\">\n                ")
                                  .append(columnName)
                                  .append(",\n            </if>\n");
                
                // 插入值带test条件
                insertValuesWithTest.append("            <if test=\"")
                                  .append(testCondition)
                                  .append("\">\n                #{")
                                  .append(camelCaseColumnName)
                                  .append("},\n            </if>\n");
                
                // 批量插入字段带test条件
                String batchTestCondition = "list[0]." + camelCaseColumnName + " != null";
                if (isStringType(columnType)) {
                    batchTestCondition += " and list[0]." + camelCaseColumnName + " != ''";
                }
                batchInsertFieldsWithTest.append("            <if test=\"")
                                       .append(batchTestCondition)
                                       .append("\">\n                ")
                                       .append(columnName)
                                       .append(",\n            </if>\n");
                
                // 批量插入值带test条件
                String itemTestCondition = "item." + camelCaseColumnName + " != null";
                if (isStringType(columnType)) {
                    itemTestCondition += " and item." + camelCaseColumnName + " != ''";
                }
                batchInsertValuesWithTest.append("                <if test=\"")
                                       .append(itemTestCondition)
                                       .append("\">\n                    #{item.")
                                       .append(camelCaseColumnName)
                                       .append("},\n                </if>\n");
                
                // 更新字段带test条件
                updateFieldsWithTest.append("            <if test=\"")
                                  .append(testCondition)
                                  .append("\">\n                ")
                                  .append(columnName)
                                  .append(" = #{")
                                  .append(camelCaseColumnName)
                                  .append("},\n            </if>\n");
                
                // where条件带test条件
                whereConditionsWithTest.append("            <if test=\"")
                                     .append(testCondition)
                                     .append("\">\n                AND ")
                                     .append(columnName)
                                     .append(" = #{")
                                     .append(camelCaseColumnName)
                                     .append("}\n            </if>\n");
            }
            
            // 添加到批量插入或更新字段列表
            batchAddOrUpdateFields.append("            ")
                                    .append(columnName)
                                    .append(",\n");
            
            // 添加到批量插入或更新值列表
            batchAddOrUpdateValues.append("            #{item.")
                                    .append(camelCaseColumnName)
                                    .append("},\n");
            
            // 添加到ON DUPLICATE KEY UPDATE列表
            if (!columnName.equals(primaryKey)) {
                duplicateKeyUpdate.append("            ")
                                .append(columnName)
                                .append("=VALUES(")
                                .append(columnName)
                                .append("),\n");
            }
        }
        
        // 去除最后的多余字符
        String fieldsStr = fields.toString().replaceAll(", $", "");
        // 去除最后的换行和逗号
        String insertFieldsStr = insertFields.toString().replaceAll(",\n$", "\n");
        String insertValuesStr = insertValues.toString().replaceAll(",\n$", "\n");
        String batchInsertValuesStr = batchInsertValues.toString().replaceAll(",\n$", "\n");
        String updateFieldsStr = updateFields.toString().replaceAll(",\n$", "\n");
        
        // 去除最后的逗号和换行
        String batchAddOrUpdateFieldsStr = batchAddOrUpdateFields.toString().replaceAll(",\n$", "\n");
        String batchAddOrUpdateValuesStr = batchAddOrUpdateValues.toString().replaceAll(",\n$", "\n");
        String duplicateKeyUpdateStr = duplicateKeyUpdate.toString().replaceAll(",\n$", "\n");
        
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/mapper.xml.template");
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("tableName", tableName);
        params.put("resultMap", resultMap.toString());
        params.put("fields", fieldsStr);
        params.put("insertFieldsWithTest", insertFieldsWithTest.toString());
        params.put("insertValuesWithTest", insertValuesWithTest.toString());
        params.put("batchInsertFieldsWithTest", batchInsertFieldsWithTest.toString());
        params.put("batchInsertValuesWithTest", batchInsertValuesWithTest.toString());
        params.put("updateFieldsWithTest", updateFieldsWithTest.toString());
        params.put("whereConditionsWithTest", whereConditionsWithTest.toString());
        params.put("batchAddOrUpdateFields", batchAddOrUpdateFieldsStr);
        params.put("batchAddOrUpdateValues", batchAddOrUpdateValuesStr);
        params.put("duplicateKeyUpdate", duplicateKeyUpdateStr);
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/resources/mapper/" + className + "Mapper.xml", content);
    }

    private static String getJdbcType(String columnType) {
        switch (columnType.toLowerCase()) {
            case "int":
            case "integer":
                return "INTEGER";
            case "varchar":
            case "char":
                return "VARCHAR";
            case "text":
                return "LONGVARCHAR";
            case "bigint":
                return "BIGINT";
            case "datetime":
            case "timestamp":
                return "TIMESTAMP";
            case "date":
                return "DATE";
            case "decimal":
                return "DECIMAL";
            default:
                return "VARCHAR";
        }
    }

    private static void generateService(String className) throws Exception {
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/service.template");
        String serviceVarName = className.substring(0, 1).toLowerCase() + className.substring(1);
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("serviceVarName", serviceVarName);
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/service/" + className + "Service.java", content);
    }

    private static void generateController(String className) throws Exception {
        String templateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/controller.template");
        
        // 计算 service 变量名（首字母小写）
        String serviceVarName = className.substring(0, 1).toLowerCase() + className.substring(1) + "Service";
        
        Map<String, Object> params = new HashMap<>();
        params.put("package", BASE_PACKAGE);
        params.put("className", className);
        params.put("serviceVarName", serviceVarName);  // 添加 service 变量名
        
        String content = TemplateUtil.processTemplate(templateContent, params);
        TemplateUtil.writeFile("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/controller/" + className + "Controller.java", content);
    }

    private static String mapColumnType(String columnType) {
        switch (columnType.toLowerCase()) {
            case "int":
            case "integer":
                return "Long";
            case "varchar":
            case "char":
            case "text":
                return "String";
            case "bigint":
                return "Long";
            case "datetime":
            case "timestamp":
                return "Date";
            case "date":
                return "Date";
            case "decimal":
                return "BigDecimal";
            default:
                return "String";
        }
    }

    // 添加判断是否为字符串类型的方法
    private static boolean isStringType(String columnType) {
        columnType = columnType.toLowerCase();
        return columnType.contains("char") || 
               columnType.contains("text") || 
               columnType.equals("varchar") || 
               columnType.equals("string");
    }

    private static void generateConverter(String className) throws Exception {
        // 检查BaseConverter是否已存在
        File baseConverterFile = new File("src/main/java/" + BASE_PACKAGE.replace('.', '/') + "/converter/BaseConverter.java");
        
        if (!baseConverterFile.exists()) {
            // 如果不存在，创建新的BaseConverter
            String baseTemplateContent = TemplateUtil.readFile(TEMPLATE_PATH + "/base.converter.template");
            Map<String, Object> baseParams = new HashMap<>();
            baseParams.put("package", BASE_PACKAGE);
            String baseContent = TemplateUtil.processTemplate(baseTemplateContent, baseParams);
            TemplateUtil.writeFile(baseConverterFile.getPath(), baseContent);
        }
        
        // 读取现有的BaseConverter内容
        String currentContent = new String(Files.readAllBytes(baseConverterFile.toPath()));
        
        // 在接口结束前添加新的转换方法
        StringBuilder newMethods = new StringBuilder();
        newMethods.append("\n    // ").append(className).append(" 转换方法\n")
                  // Param -> PO
                  .append("    ").append(className).append("PO convertTo")
                  .append(className).append("PO(").append(className).append("Param param);\n\n")
                  // List<Param> -> List<PO>
                  .append("    List<").append(className).append("PO> convertTo")
                  .append(className).append("PO(List<").append(className).append("Param> paramList);\n\n")
                  // PO -> VO
                  .append("    ").append(className).append("VO convertTo")
                  .append(className).append("VO(").append(className).append("PO po);\n\n")
                  // List<PO> -> List<VO>
                  .append("    List<").append(className).append("VO> convertTo")
                  .append(className).append("VO(List<").append(className).append("PO> poList);\n");
        
        // 在接口结束前插入新方法
        String updatedContent = currentContent.replace("}", newMethods + "}\n");
        
        // 添加新的import语句
        String importStatements = generateImportStatements(className, BASE_PACKAGE);
        updatedContent = insertImports(updatedContent, importStatements);
        
        // 写回文件
        Files.write(baseConverterFile.toPath(), updatedContent.getBytes());
    }

    private static String generateImportStatements(String className, String basePackage) {
        return String.format(
            "import %s.model.po.%sPO;\n" +
            "import %s.model.dto.%sDTO;\n" +
            "import %s.model.vo.%sVO;\n" +
            "import %s.model.param.%sParam;\n",
            basePackage, className,
            basePackage, className,
            basePackage, className,
            basePackage, className
        );
    }

    private static String insertImports(String content, String imports) {
        // 在package语句后插入import语句
        int packageEnd = content.indexOf(";") + 1;
        return content.substring(0, packageEnd) + "\n" + imports + content.substring(packageEnd);
    }

    // 将方法改为static，这样可以在其他静态方法中调用
    private static String generateVoClassName(String tableName) {
        String className = convertToCamelCase(tableName);
        return className + "VO";
    }

    private static String generateDtoClassName(String tableName) {
        String className = convertToCamelCase(tableName);
        return className + "DTO";
    }

    private static String generatePoClassName(String tableName) {
        String className = convertToCamelCase(tableName);
        return className + "PO";
    }

    // 在CodeGenerator类中添加这个方法
    private static String convertToCamelCase(String tableName) {
        // 如果表名以't_'或'tbl_'开头，去掉这个前缀
        if (tableName.startsWith("t_") || tableName.startsWith("tbl_")) {
            tableName = tableName.substring(tableName.indexOf('_') + 1);
        }
        
        StringBuilder result = new StringBuilder();
        // 标记否是新单词的开始
        boolean nextUpperCase = true;
        
        for (int i = 0; i < tableName.length(); i++) {
            char c = tableName.charAt(i);
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    result.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        
        return result.toString();
    }

    // 修改generateFields方法，确保生成@TableField注解
    private static void generateFields(ResultSet columns, StringBuilder fields) throws Exception {
        // 定义BasePO中已有的字段集合（除了id）
        Set<String> basePoFields = new HashSet<>();
        basePoFields.add("createTime");
        basePoFields.add("updateTime");
        basePoFields.add("createBy");
        basePoFields.add("updateBy");
        
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String camelCaseColumnName = toCamelCase(columnName);
            String columnType = columns.getString("TYPE_NAME");
            String remarks = columns.getString("REMARKS");
            String javaType = mapColumnType(columnType);
            
            // 跳过BasePO中已有的字段（除了id）
            if (basePoFields.contains(camelCaseColumnName) && !"id".equals(columnName)) {
                continue;
            }
            
            fields.append("    /**\n")
                  .append("     * ").append(remarks).append("\n")
                  .append("     */\n");
            
            // 如果是id字段，添加@TableId注解
            if ("id".equals(columnName)) {
                fields.append("    @TableId(value = \"").append(columnName).append("\", type = IdType.ASSIGN_ID)\n");
            } else {
                // 为非id字段添加@TableField注解
                fields.append("    @TableField(value = \"").append(columnName).append("\")\n");
            }
            
            fields.append("    @ApiModelProperty(value = \"").append(remarks).append("\")\n")
                  .append("    private ").append(javaType)
                  .append(" ").append(camelCaseColumnName).append(";\n\n");
        }
    }
} 